package com.csxh.util;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.csxh.eshop.bean.Order;

public class JPAUtil {

	private static final Log logger = LogFactory.getLog(JPAUtil.class);
	private static final String unitName = "jpa";
	private static final EntityManagerFactory factory;
	static {
		factory = Persistence.createEntityManagerFactory(unitName);
	}

	private static final ThreadLocal<EntityManager> entityManagers;
	static {
		entityManagers = new ThreadLocal<EntityManager>();
	}

	public static EntityManager openEntityManager() {
		EntityManager em = entityManagers.get();
		if (null == em) {
			em = factory.createEntityManager();
			entityManagers.set(em);
		}
		return em;
	}

	public static void closeEntityManager(EntityManager em) {
		if (null != em) {
			em.close();
			em = null;
		}
		entityManagers.remove();
	}

	public static void closeEntityManagerFactory() {
		factory.close();

	}

	public static void main(String[] args) {
		EntityManager em = null;

		try {
			em = JPAUtil.openEntityManager();

			em.getTransaction().begin();
			
			em.getTransaction().commit();

		} catch (Exception e) {
			em.getTransaction().rollback();
			logger.error(e.getMessage());
			throw e;
		} finally {
			JPAUtil.closeEntityManager(em);
			JPAUtil.closeEntityManagerFactory();
		}

	}

	public static void m1(String[] args) {

		EntityManager em = null;

		try {
			em = JPAUtil.openEntityManager();
			// jpaql->hql
			Query query = em.createQuery("select o from Order o");
			List<Order> list = query.getResultList();
			System.out.println(list.size());

		} catch (Exception e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			JPAUtil.closeEntityManager(em);
			JPAUtil.closeEntityManagerFactory();
		}

	}

}
